//
//  BHViewManager.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/6/10.
//

import Foundation
import UIKit

extension UIWindow {
    static var keyWindow: UIWindow {
        get {
            return (UIApplication.shared.delegate!.window!)!
        }
    }
}

extension BHTabbarController {
    static var tabbarController: BHTabbarController {
        let root = UIWindow.keyWindow.rootViewController!
        return root as! BHTabbarController
    }
}

extension BHNavigationController {
    static var currentNavigationController: BHNavigationController? {
        get {
            let root = UIWindow.keyWindow.rootViewController!
            if  root is BHTabbarController {
                let tabbar = root as! BHTabbarController
                return tabbar.selectedViewController as? BHNavigationController
            }else {
                if root is BHNavigationController {
                    return root as? BHNavigationController
                }else {
                    return nil
                }
            }
        }
    }
}

extension BHBaseViewController {
    static var currentViewController: UIViewController? {
        get {
            let root = UIWindow.keyWindow.rootViewController!
            if  root is BHTabbarController {
                let tabbar = root as! BHTabbarController
                if tabbar.presentingViewController != nil {
                    return tabbar.presentingViewController
                }else {
                    let nav = tabbar.selectedViewController as? BHNavigationController
                    if nav?.presentingViewController != nil {
                        return nav?.presentingViewController
                    }else {
                        return nav?.visibleViewController
                    }
                }
            }else {
                if root is BHNavigationController {
                    let nav = root as! BHNavigationController
                    if nav.presentingViewController != nil {
                        return nav.presentingViewController
                    }else {
                        return nav.visibleViewController
                    }
                }else {
                    return root
                }
            }
        }
    }
}
